package com.letoken.platform.repo.admin.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.letoken.platform.repo.admin.redis.AppChainNodeRedis;
import com.letoken.platform.repo.app.dao.BlockchainMapper;
import com.letoken.platform.repo.app.po.Blockchain;
import com.letoken.platform.repo.repo.dao.AppChainNodeMapper;
import com.letoken.platform.repo.repo.po.AppChainNode;
import com.letoken.platform.repo.wallet.manager.Web3ChainProviderManager;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

/**
 * @author wyl
 * @date 2023/1/31 18:24
 * @Version 1.0
 */
@Log4j2
@Repository
public class AppChainNodeManager {

    @Autowired
    private AppChainNodeMapper appChainNodeMapper;

    @Autowired
    private Web3ChainProviderManager web3ChainProviderManager;

    /**
     * 查询是否有重复的网络标识和网络名称
     *
     * @param nodeName nodeName
     * @return return
     */
    public boolean queryNodeName(String nodeName) {
        LambdaQueryWrapper<AppChainNode> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AppChainNode::getNodeName, nodeName);
        Integer count = appChainNodeMapper.selectCount(queryWrapper);
        return count > 0;
    }

    /**
     * 获取速度较快的节点URL
     * @param chainName
     * @return
     */
    public String getQuickNodeUrl(String chainName) {
        String url = AppChainNodeRedis.me().getQuickNode(chainName);
        if (StringUtils.isEmpty(url)) {
            return web3ChainProviderManager.getProvider(chainName).getEndpoint();
        }
        return url;
    }

    public void UpdateNodeSpeed(String chainName, String url, Integer speed) {
        if (speed > 0) {
            AppChainNodeRedis.me().set(chainName, url, speed);
        }
    }
}
